package java_thinking.unit_17._17_7_8;

import java_thinking.net.mindview.util.TextFile;

import java.util.List;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2019/4/17 20:45
 */

class AssociativeArray<K,V> {
    private Object[][] pairs;
    private int index;
    public AssociativeArray(int index) {
        pairs = new Object[index][2];
    }
    public void put(K key,V value) {
        for (int i = 0; i < pairs.length; i++) {
            if (key.equals(pairs[i][0])) {
                pairs[i] = new Object[]{key,value};
                return;
            }
        }
        if (index >= pairs.length) {
            throw new ArrayIndexOutOfBoundsException();
        }
        pairs[index++] = new Object[]{key,value};
    }

    public V get(K key) {
        for (int i = 0; i < pairs.length; i++) {
            if (key.equals(pairs[i][0])) {
                return (V) pairs[i][1];
            }
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (int i = 0; i < index; i++) {
            builder.append(pairs[i][0].toString());
            builder.append(" : ");
            builder.append(pairs[i][1].toString());
            if (i < index -1) {
                builder.append(" , ");
            }
        }
        builder.append("]");
        return builder.toString();
    }
}
public class E13_WordCounter {
    public static void main(String[] args) {
        List<String> words = new TextFile("test3.txt","\\W+");
        AssociativeArray<String,Integer> array = new AssociativeArray<>(words.size());
        for (String s : words) {
            Integer integer = array.get(s);
            array.put(s,integer == null ? 1 : integer+ 1);
        }
        System.out.println(array);
    }
}
